//controllers层，封装对应路由请求的async异步函数，封装相对应的处理方法

//引入模型model，用于操作数据
const stuModle = require('../models/student')

//增
const studentAdd = async (ctx, next) => {
  console.log('参数query', ctx.query)
  let { name, age } = ctx.query
  if(name.length===0 || age.length===0 || age <=0){
    ctx.body = {
      code: 500,
      message: '信息不能为空'
    }
    return
  }
  
  //操作集合中的数据（向表中增加数据）
  let result = await stuModle.handleAdd(name, age)
  console.log('操作完后返回结果', result)
  if(result.status === 1){
    ctx.body = {
      code: 200,
      message: '添加成功',
      data: result
    }
  }else{
    ctx.body = {
      code: 500,
      message: '操作失败'
    }
  }
}

//删
const studentDel = async (ctx, next) => {
  const id = ctx.query.ids
  if(!id){
    ctx.body = {
      code: 500,
      message: 'id为空，记录不存在'
    }
    return
  }
  let result = await stuModle.handleDel(id)
  if(result.status === 1){
    ctx.body = {
      code: 200,
      message: '删除成功'
    }
  }else{
    ctx.body = {
      code: 500,
      message: '删除失败'
    }
  }
}

//改
const studentUpdate = async (ctx, next) => {
  const { id, name, age } = ctx.query
  if(name && name.length===0){
    ctx.body = {
      code: 500,
      massage: 'name不能为空'
    }
    return
  }

  if(age && age.length===0){
    ctx.body = {
      code: 500,
      massage: 'age不能为空'
    }
    return
  }

  let result = await stuModle.handleUpdate(id, name, age)
  if(result.status === 1){
    ctx.body = {
      code: 200,
      message: '修改成功',
      data: result
    }
  }else{
    ctx.body = {
      code: 500,
      message: '修改失败'
    }
  }

}

//查
const studentFind = async (ctx, next) => {
  const name = ctx.query.name
  let result = await stuModle.handleFind(name)
  if(result.status === 1){
    ctx.body = {
      code: 200,
      message: '查询成功',
      data: result
    }
  }else{
    ctx.body = {
      code: 500,
      message: '查询失败'
    }
  }
}

module.exports = {
  studentAdd,
  studentDel,
  studentUpdate,
  studentFind 
}